<?php
namespace Home\Controller;
use Think\Controller;
use Think\Auth;
class UserController extends BaseController {
	public function index(){
		session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$result = $Form -> where("uname='{$uname}'")->select();
		if($result){
			$this->assign("result",$result[0]);
			$this->display();
		}else{
			$this -> error('没有要查找的信息！');
		}
	}	
	public function myself(){
		session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$result = $Form -> where("uname='{$uname}'")->select();
		$ag= M('auth_group_access');
		$result2 = $ag ->join("think_auth_group on think_auth_group.id=think_auth_group_access.group_id")-> where("uid={$result[0]['uid']}")->select();
		if($result){
			$this->assign("result",$result[0]);
			$this->assign("result2",$result2[0]);
			$this->display();
		}else{
			$this -> error('没有要查找的信息！');
		}
	}
	//修改密码
	public function update(){
        session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$result = $Form -> where("uname='{$uname}'")->select();
		if($result){
			$this->assign("result",$result[0]);
		}else{
			$this -> error('没有要查找的信息！');
		}
		
		if(IS_POST){
			$obj=(object)[];
			$obj->code=0;
			$obj->message="修改成功";
			$obj->data=$_POST;
			$Form = D('user');
		   if ($Form -> create()) {
			$result = $Form ->where("uname='{$uname}'")-> save();
			if ($result) {
				$this->ajaxReturn($obj);
			} else {
				$this -> error('写入错误！');
			}
		   } else {
			$this -> error($Form -> getError());
		   }
		}else{
			$obj=(object)[];
			$obj->code=1;
			$obj->message="修改失败";
			$this->display();
		}
	}
	public function rlist(){
		$ag = M('auth_group');
		session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$res = $Form ->join('think_auth_group_access on(think_user.uid=think_auth_group_access.uid)')-> where("uname='{$uname}'")->select();
		$result = $ag->select();
		$obj=(object)[];
		$obj->data=array();
		for ($i=0; $i <count($result) ; $i++) { 
			if($res[0]["group_id"]<=$result[$i]["id"]){
				$obj->data[]=$result[$i]["title"];
			}
		}
		if($result){
			$this->ajaxReturn($obj);
		}else{
			$this -> error('没有要查找的信息！');
		}
	}
	//用户列表页面的操作
	public function lists(){
		session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$result = $Form -> where("uname='{$uname}'")->select();
		if($result){
			$this->assign("result",$result[0]);
		}else{
			$this -> error('没有要查找的信息！');
		}
		//添加新用户
		if(IS_POST){
			$obj=(object)[];
			$obj->code=0;
			$obj->message="添加成功";
			$obj->data=$_POST;
			$F = D('user');
			$ag = M('auth_group');
			$re=$F->where("nickname='{$_POST["nickname"]}' or uname='{$_POST["uname"]}' ")->select();
			if($obj->data["add"]){
				if(!is_null($re)){
					if ($F -> create()) {
						$result = $F ->add();
						if ($result) {
							$u = M('user');
							$uid=$u->where("nickname='{$_POST["nickname"]}'")->select();
							$result1=$ag->where("title='{$_POST['role']}'")->select();
					        $data["group_id"]=$result1[0]["id"];
					        $data["uid"]=$uid[0]["uid"];
					        $aga = D('auth_group_access');
					        $result2=$aga->add($data);
							if($result2){
							$this->ajaxReturn($obj);
							}
						} else {
							$this -> error('添加错误！');
						}
					}else {
						$this -> error($Form -> getError());
					} 
				}else{
//					$this -> error('姓名重复！');
				}
			}else if($obj->data["update"]){
			   //编辑用户
			   if(!is_null($re)){
				if ($F -> create()) {
					$reg = $F ->where("nickname='{$obj->data["nc"]}'")-> save();
					if ($reg) {
						$this->ajaxReturn($obj);
					} else {
						$this -> error('写入错误！');
					}
				} else {
					$this -> error($F -> getError());
				}
			   }else{
					$this -> error('姓名重复！');
				}
			}
		}else{
			$obj=(object)[];
			$obj->code=1;
			$obj->message="添加失败";
			$this->display();
		}
	}
	public function roles(){
		session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$result = $Form -> where("uname='{$uname}'")->select();
		if($result){
			$this->assign("result",$result[0]);
		}else{
			$this -> error('没有要查找的信息！');
		}
		//添加新用户
		if(IS_POST){
			$obj=(object)[];
			$obj->code=0;
			$obj->message="添加成功";
			$obj->data=$_POST;
			$F = D('Auth_group');
			if($obj->data["add"]){
				//添加
				if ($F -> create()) {
					$result = $F ->add();
					if ($result) {
						$this->ajaxReturn($obj);
					} else {
						$this -> error('添加错误！');
					}
				} else {
					$this -> error($F -> getError());
				}
			}
			else if($obj->data["update"]){
				//编辑
				if ($F -> create()) {
					$result = $F ->where("title='{$obj->data["ut"]}'")-> save();
					if ($result) {
						$this->ajaxReturn($obj);
					} else {
						$this -> error('写入错误！');
					}
				} else {
					$this -> error($F -> getError());
				}
			}
		}else{
			$obj=(object)[];
			$obj->code=1;
			$obj->message="添加失败";
			$this->display();
		}
	}
	public function auth(){
		session_start();
		$uname=$_SESSION["uname"];
		$Form = M('user');
		$result = $Form -> where("uname='{$uname}'")->select();
		if($result){
			$this->assign("result",$result[0]);
			$this->display();
		}else{
			$this -> error('没有要查找的信息！');
		}
	}
//显示列表
	public function serverlist(){
		$m=M("user");
		$columnindex=$_GET["order"][0]["column"];	
		$dir=$_GET["order"][0]["dir"];	
		$start=$_GET["start"];	
		$length=$_GET["length"];		
		$search=$_GET["search"]["value"];
		if ($columnindex==1) {
				$column="nickname";
			} else if($columnindex==2){
				$column="email";
			}  else if($columnindex==3){
				$column="phone";
			}  else if($columnindex==4){
				$column="address";
			}  else if($columnindex==6){
				$column="uname";
			}else if($columnindex==7){
				$column="time";
			}else{
				$column="uid";
			}
		$result=$m->where("nickname like '%{$search}%' or uname like '%{$search}%' or phone like '%{$search}%' or email like '%{$search}%' or address like '%{$search}%'")->order("time desc")->limit($start,$length)->select();
		$reg=(object)[];
		    $reg->data=array();
			$reg->draw=$_GET["draw"];
			$reg->search=$search;
		    for ($i=0; $i <count($result) ; $i++) {
		    	$aga=M("auth_group_access");
		    	$title=$aga->join("think_auth_group ON think_auth_group_access.group_id=think_auth_group.id")->where("uid={$result[$i]["uid"]}")->select();
		    	$reg->data[]=array($i+1,$result[$i]["nickname"],$result[$i]["email"],$result[$i]["phone"],$result[$i]["address"],$result[$i]["birthday"],$title[0]["title"],$result[$i]["uname"],$result[$i]["time"]);
		    }
			$Model =new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
			$result=$Model->query("select count(*) from think_user where nickname like '%{$search}%' or email like '%{$search}%' or address like '%{$search}%'");
			$reg->recordsFiltered=$result[0]["count(*)"]*1;		
			$reg->recordsTotal=100;	
			$this->ajaxReturn($reg);
	}
	//角色列表
	public function authitem(){
		session_start();
		$uname=$_SESSION["uname"];
		$u=M("user");
		$group_id=$u->join("think_auth_group_access on think_auth_group_access.uid=think_user.uid")->where("uname='{$uname}'")->select();
		$ag=M("auth_group");
		$columnindex=$_GET["order"][0]["column"];	
		$dir=$_GET["order"][0]["dir"];	
		$start=$_GET["start"];	
		$length=$_GET["length"];		
		$search=$_GET["search"]["value"];
		if ($columnindex==1) {
				$column="title";
			}else{
				$column="id";
			}
		$result=$ag->where("title like '%{$search}%'")->order($column." ".$dir)->limit($start,$length)->select();
		$reg=(object)[];
		    $reg->data=array();
			$reg->draw=$_GET["draw"];
			$reg->search=$search;
		    for ($i=0; $i <count($result) ; $i++) {
		    	if($group_id[0]["group_id"]<=$result[$i]["id"]){ 
		    	$reg->data[]=array($i+1,$result[$i]["title"],$result[$i]["status"]);
				}
		    }
			$Model =new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
			$result1=$Model->query("select count(*) from think_auth_group where title like '%{$search}%' or rules like '%{$search}%'");
			$reg->recordsFiltered=$result1[0]["count(*)"]*1;		
			$reg->recordsTotal=100;	
			$this->ajaxReturn($reg);
	}
//授权列表
	public function authshou(){
		$title=$_POST["title"];
		$ar=M("auth_rule");
		$ag=M("auth_group");
		$rules=$ag->where("title='{$title}'")->select();
		//只可授权方法
		$result1=$ar->field("title")->where("title not in(".$rules[0]["rules"].") and is_menu =0")->select();
		$this->ajaxReturn($result1);
	}
	//添加授权
	public function shouadd(){
		if(IS_POST){
		$data[]=$_POST;
		$ar=M("auth_rule");
		$title=$data[0]['title'];
		$auth=$data[0]['auth'];
		//查询当前选中的详细信息
		$result1=$ar->where("title='{$title}'")->select();
		//父标签的id也跟着方法的授权而授权
		$pid=$ar->where("id='{$result1[0]["pid"]}'")->select();
		$ag=M("auth_group");
		$result2=$ag->field("rules")->where("title='{$auth}'")->select();
		if($pid[0]["pid"]==1||$pid[0]["pid"]==2){
		$rules=$result2[0]["rules"].",".$result1[0]["id"].",".$pid[0]["id"].",".$pid[0]["pid"];
		}else{
		$rules=$result2[0]["rules"].",".$result1[0]["id"].",".$pid[0]["id"];
		}
		$data["rules"]=$rules;
		$result3=$ag->where("title='{$auth}'")->save($data);
		if ($result3) {
			$obj=(object)[];
			$obj->code=0;
			$obj->data=$result1;
			$this->ajaxReturn($obj);
		} else {
			$this -> error('写入错误！');
		}
	}
	}
	//删除权限
	public function shoudele(){
		if(IS_POST){
		$data[]=$_POST;
		$title=$data[0]['title'];
		$auth=$data[0]['auth'];
		$ag=M("auth_group");
		$result1=$ag->where("title='{$auth}'")->select();
		$ar=M("auth_rule");
		$id=$ar->where("title='{$title}'")->select();
		//判断当前方法是否还拥有其他的方法共用的子菜单
		$child=$ar->where("pid={$id[0]['pid']} and id in (".$result1[0]["rules"].") and id !={$id[0]['id']}")->select();	
		$str="";//拼接字符串,新的权限字符串
		if(count($child)==0){
			//没有别的方法在，则需要删除该子标签
			$pid=$ar->where("id={$id[0]['pid']}")->select();
			$child2=$ar->where("pid={$pid[0]["pid"]} and id in (".$result1[0]["rules"].") and id !={$pid[0]['id']}")->select();
			if(count($child2)==0){
				//若只有一个子标签，则还需要删除其父标签
			$ppid=$ar->where("id={$pid[0]['pid']}")->select();
			$str.=$id[0]["id"].",".$pid[0]["id"].",".$ppid[0]["id"];
			}else{
			$str.=$id[0]["id"].",".$pid[0]["id"];	
			}
		}else{
			//有别的方法在则只删除该方法
			$str.=$id[0]["id"];
		}
		$result2=$ar->where("id in (".$result1[0]["rules"].") and id not in(".$str.")")->select();
		$newrule="";
		for ($i=0; $i <count($result2) ; $i++) {
			if($i<count($result2)-1){
				$newrule.=$result2[$i]["id"].",";
			}else{
				$newrule.=$result2[$i]["id"];
			}
		}
		//编辑rules
		$data["rules"]=$newrule;
		$result3=$ag->where("title='{$auth}'")->save($data);
		if ($result3) {
			$obj=(object)[];
			$obj->code=0;
			$obj->data=$result1;
			$this->ajaxReturn($obj);
		} else {
			$this -> error('写入错误！');
		}
	}
	}
//  public function listfor(){
//		if(IS_GET){
//			$list=array();
//		    for($i=0;$i<1000;$i++){
//			//内存数据库
//			$arr=array($i,"姓名".$i,rand(10, 100),rand(0, 1)?"男":"女");		       
//		       $arr[]="<button type='button' class='btn btn-default btn-sm'>查看</button><button type='button' class='btn btn-default btn-sm'>删除</button><button type='button' class='btn btn-default btn-sm'>编辑</button>";
//		       $list[]=$arr;
//		   
//		}
//			$columnindex=$_GET['order'][0]['column'];
//			$dir=$_GET['order'][0]['dir'];
//			$start=$_GET['start'];
//			$length=$_GET['length'];
//			$search=$_GET['search']['value'];
//			$ret=(object)[];
//			$ret->data=array();
//			$ret->draw=$_GET['draw'];
//			$ret->search=$search;			
//			$count=0;		
//			for($i=0;$i<count($list);$i++){
//             if($search==""?true:false||strchr($list[$i][1],$search)||strchr($list[$i][2],$search)||strchr($list[$i][3],$search)){
//							
//						$count++;
//						if($i>=$start&&count($ret->data)<$length){
//							$ret->data[]=$list[$i];
//						}
//					
//				}
//			}
//			$ret->recordsFiltered=$count;
//			$ret->recordsTotal=1000;
//			$this->ajaxReturn($ret);
//		}	
//	}
//列表页面的删除
public function delete(){
	$Form = D('user');
	if(IS_POST){
		$data[]=$_POST;
		$nickname=$data[0]['nickname'];
		$aga = D('auth_group_access');
		$u = M('user');
		$re=$u->where("nickname='{$nickname}'")->select();
		$re2=$aga->where("uid={$re[0]["uid"]}")->delete();
		if ($re2) {
		$result=$Form->where("nickname='{$nickname}'") -> delete();
			if($result){
			$this -> success('删除成功！');
			}
			} 
		else {
				$this -> error('删除错误！');
			}
	}
}
//删除角色
public function dele(){
	$Form = D('Auth_group');
	if(IS_POST){
		$data[]=$_POST;
		$title=$data[0]['title'];
		$aga = M('auth_group_access');
		$result=$aga->join("think_auth_group ON think_auth_group_access.group_id=think_auth_group.id")->where("title='{$title}'")->select();
		if(is_null($result[0])){
		$result1=$Form->where("title='{$title}'") -> delete();
		if ($result1) {
				$this -> success('删除成功！');
			} else {
				$this -> error('删除错误！');
			}
		}else{
			$obj=(object)[];
			$obj -> code=1;
			$obj -> message="该角色不能删除！";
			$this->ajaxReturn($obj);
		}
	}
}
//角色用户列表
public function rulelist(){
	if(IS_POST){
	$data[]=$_POST;
	$title=$data[0]['title'];
	$aga = M('auth_group_access');
	$result1 = $aga->field("uid")->join("think_auth_group ON think_auth_group.id=think_auth_group_access.group_id")->where("title='{$title}'") ->select();
	$user=M('user'); 
	for ($i=0; $i <count($result1) ; $i++) {
	$result2[]=$user->where("uid in (".$result1[$i]["uid"].")") ->select();	
	}
	$reg=(object)[];
	$reg->data=array();
	for($i=0; $i <count($result2) ; $i++) {
	    $reg->data[]=array($i+1,$result2[$i][0]["nickname"],$result2[$i][0]["uname"]); 	
	}
	$this->ajaxReturn($reg);
}
}
public function authrules(){
	if(IS_POST){
	$data[]=$_POST;
	$title=$data[0]['title'];
	$ag = M('auth_group');
	$result1 = $ag->field("rules")->where("title='{$title}'") ->select();
	$ar = M('auth_rule');
	$result2= $ar->field("title")->where("id in (".$result1[0]["rules"].") and is_menu =0") ->select();
	$reg=(object)[];
	for ($i=0; $i <count($result2) ; $i++) { 
		for ($k=0; $k < count($result2[$i]); $k++) { 
			$reg->data[]=$result2[$i]["title"];
		}
	}
	$this->ajaxReturn($reg);
	}
}
//角色用户选择列表
	public function ruleuser(){
		$username=$_POST["username"];
		$u=M("user");
		$result1=$u->where("uname not in(".$username.")")->select();
		$str="";
		//拼接字符串,新的权限字符串
		for ($i=0; $i <count($result1) ; $i++) {
			if($i<count($result1)-1){
			$str.=$result1[$i]["uid"].",";
			}else{
			$str.=$result1[$i]["uid"];
			}
		}
		$ag=M("auth_group");
		$group_id=$ag->where("title='{$_POST["title"]}'")->select();
		$aga=M("auth_group_access");
		$result2=$aga->join("think_auth_group ON think_auth_group.id=think_auth_group_access.group_id")->where("uid in (".$str.")")->select();
		$list=(object)[];
		for ($i=0; $i <count($result2) ; $i++) {
			//判断当前用户的角色id与
			if($group_id[0]["id"]<$result2[$i]["group_id"]){
				$list->nickname[]=$result1[$i]["nickname"];
				$list->title[]=$result2[$i]["title"];
			} 
		}
		$this->ajaxReturn($list);
	}
	//添加角色用户
	public function ruleadd(){
		if(IS_POST){
		$data[]=$_POST;
		$u=M("user");
		$result1=$u->where("nickname like '".$data[0]["nickname"]."'")->select();
		$ag=M("auth_group");
		$result2=$ag->field("id")->where("title like '".$data[0]["title"]."'")->select();
		$aga=M("auth_group_access");
		$data["group_id"]=$result2[0]["id"];
		$result3=$aga->where("uid={$result1[0]["uid"]}")->save($data);
		if ($result3) {
			$obj=(object)[];
			$obj->code=0;
			$obj->data=$result1;
			$this->ajaxReturn($obj);
		} else {
			$this -> error('写入错误！');
		}
		}
		
	}
	//删除角色用户
	public function ruledele(){
		session_start();
		$uname=$_SESSION["uname"];
		if(IS_POST){
		$data[]=$_POST;
		$u=M("user");
		$result1=$u->join("think_auth_group_access on think_auth_group_access.uid=think_user.uid")->where("nickname like '".$data[0]["nickname"]."'")->select();
		$ag=M("auth_group");
		$result2=$ag->field("id")->where("title like '".$data[0]["title"]."'")->select();
		if($result2[0]["id"]){}
		}
		
	}
public function out(){
	$out=$_POST["out"];
if($out){
	//删除回话内容
	session_unset();
}
}
}
